<?php
include("../../header.inc");
require_once("../../DataBase.inc");
require_once("../../general_queries.inc");

$programs = query_programs()->execute();

foreach ($programs as $p) {
	// get the minimum marks
	$result = Query::query_sql("SELECT * FROM interview_eligibility_rule WHERE selection_campaign_id=".$_SESSION["campaign_id"]." AND program_id=".$p["program_id"]);
	if ($result === false || count($result) == 0) {
		echo "Warning: no rule defined for program ".$p["program_name"];
		continue;
	}
	$rule = $result[0];
	// remove eligibility if not passed
	$q = query_not_excluded_applicants();
	$q->select("applicant.applicant_id");
	$q->join("applicant_eligibility",null,array("applicant_eligibility.applicant_id=applicant.applicant_id","applicant_eligibility.program_id=".$p["program_id"]));
	$q->where("applicant_eligibility.eligible=1");
	$q->join_applicant("applicant_interview");
	$q->where("applicant_interview.interview_communication_and_maturity < ".$rule["interview_communication_and_maturity_rule"].
		" OR applicant_interview.interview_motivation_for_cist < ".$rule["interview_motivation_for_cist_rule"].
		" OR applicant_interview.interview_affinities_with_computer_or_carear_plan < ".$rule["interview_affinities_with_computer_or_carear_plan_rule"]);
	$applicants = $q->execute();
	if ($applicants <> false && count($applicants)>0) {
		$q = "UPDATE applicant_eligibility SET eligible=0 WHERE program_id=".$p["program_id"]." AND (";
		for ($i = 0; $i < count($applicants); $i++)
			$q .= ($i > 0 ? " OR " : "")."applicant_id=".$applicants[$i]["applicant_id"];
		$q .= ")";
		Query::query_sql($q);
	}
	
	echo "Rules applied for program ".$p["program_name"]."<br/>";
}

// exclude applicants being no more eligible for any program
$q = query_not_excluded_applicants();
foreach ($programs as $p) {
	$q->join("applicant_eligibility", "e".$p["program_id"], array("applicant.applicant_id="."e".$p["program_id"].".applicant_id","e".$p["program_id"].".program_id=".$p["program_id"]));
	$q->where("e".$p["program_id"].".eligible=0");
}
$q->select("applicant.applicant_id");
$applicants = $q->execute();
if ($applicants <> false && count($applicants)>0) {
	$q = "UPDATE applicant SET excluded=1,excluded_reason='Not eligible after interview' WHERE ";
	for ($i = 0; $i < count($applicants); $i++)
		$q .= ($i > 0 ? " OR " : "")."applicant_id=".$applicants[$i]["applicant_id"];
	Query::query_sql($q);
}

include("../../footer.inc");
?>
